package com.youbug.kefu.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.youbug.kefu.dto.SessionInfo;
import com.youbug.kefu.entity.Message;
import com.youbug.kefu.service.ISenderService;
import com.youbug.kefu.websocket.ChatsInfoHolder;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class SenderService implements ISenderService {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean sendMsgToClient(Long clientId, Message msg) {

        SessionInfo sessionInfo = ChatsInfoHolder.clientSessionInfoMap.get(clientId);

        return sendMsg(sessionInfo, msg);
    }

    @Override
    public boolean sendMsgToAgent(Long agentId, Message msg) {

        SessionInfo sessionInfo = ChatsInfoHolder.agentSessionInfoMap.get(agentId);

        return sendMsg(sessionInfo, msg);
    }

    private boolean sendMsg(SessionInfo sessionInfo, Message msg){
        try {
            if(sessionInfo != null){
                sessionInfo.getSession().getBasicRemote().sendText(objectMapper.writeValueAsString(msg));
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
